<template>
  <el-form class="nomal-workflow" :model="workflowNomal" ref="nomalForm" :inline="true" label-position="top">
    <el-row>
      <el-col :span="12">
        <el-form-item label="标题:" prop="title" :rules="[{ required: true, message: '请输入标题' }]">
          <el-input v-model="workflowNomal.title" placeholder="请输入标题" maxlength="256" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="分组:" prop="group" :rules="[{ required: true, message: '请输入分组' }]">
          <el-autocomplete style="width: 100%;" v-model="workflowNomal.group" :fetch-suggestions="querySearch"
            maxlength="256" placeholder="请输入分组" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="图标:" prop="icon" :rules="[{ required: true, message: '请选择图标' }]">
          <el-popover placement="bottom-start" :width="popoverWidth" trigger="click">
            <template #reference>
              <el-input v-model="workflowNomal.icon" ref="iconInput" readonlyplaceholder="请输入图标" maxlength="256" />
            </template>
            <div class="icons-container">
              <div v-for="icon in availableIcons" :key="icon" @click="selectIcon(icon)">
                <component :is="icon" :width="24" :height="24"
                  :class="{ 'el-icon-active': workflowNomal.icon === icon }" />
              </div>
            </div>
          </el-popover>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="颜色:">
          <el-input :readonly="true" v-model="workflowNomal.color">
            <template #prepend>
              <el-color-picker v-model="workflowNomal.color" size="small" :show-alpha="true"
                :predefine="predefineColors"></el-color-picker>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="描述:">
          <el-input type="textarea" v-model="workflowNomal.description"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script setup lang="ts">
import { getAllGroupAsync } from '@/utils/api/workflow/definition';
import type { WorkflowDefinition } from '@/utils/api/workflow/definition/type';
import type { ElInput, FormInstance } from 'element-plus';
import { ref, defineProps, defineEmits, computed, onMounted, defineExpose } from 'vue';
// 表单实例
const nomalForm = ref<FormInstance>();
// 图标文本框实例
const iconInput = ref<InstanceType<typeof ElInput> | null>(null);
const popoverWidth = ref<number>(420);

// 分组数据类型
interface RestaurantItem {
  value: string;
}

// 分组数据
const groups = ref<Array<RestaurantItem>>([]);
const querySearch = (queryString: string, cb: any) => {
  const results = queryString && queryString.length > 0
    ? groups.value.filter(createFilter(queryString))
    : groups.value;
  cb(results);
};
const createFilter = (queryString: string) => {
  return (groups: RestaurantItem) => {
    return (
      groups.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

// 定义图标数据
const availableIcons = ['Plus', 'Promotion', 'Avatar'];
// 图标选择事件
const selectIcon = (iconName: string) => {
  workflowNomal.value.icon = iconName;
};

// 定义props接收父组件传递的对象
const props = defineProps<{
  modelValue: WorkflowDefinition;
}>();

// 定义 emits 用于向父组件传递更新事件
const emits = defineEmits<{
  (e: 'update:modelValue', data: WorkflowDefinition): void;
}>();

// 使用 computed 从 props 创建一个可读写的本地副本，这样可以直接修改它，同时触发更新事件向父组件回传数据(即实现父子组件的数据双向绑定)
const workflowNomal = computed({
  get(): WorkflowDefinition {
    return props.modelValue;
  },
  set(newValue: WorkflowDefinition) {
    emits('update:modelValue', newValue);
  }
});

// 组件加载
onMounted(async () => {
  popoverWidth.value = getIconInputOffsetWidth();
  const allGroups = await getAllGroupAsync();
  groups.value = allGroups.map((group) => ({ value: group }));
});

// 获取 el-input 组件的根 DOM 元素
const getIconInputOffsetWidth = () => {
  const inputElement = iconInput.value?.$el as HTMLElement; // 获取 el-input 组件的根 DOM 元素
  const inputWidth = inputElement?.offsetWidth; // 获取元素
  return inputWidth || 420;
};

//颜色组件组件的数据
const predefineColors = ref([
  '#ff4500',
  '#ff8c00',
  '#ffd700',
  '#90ee90',
  '#00ced1',
  '#1e90ff',
  '#c71585',
  'rgba(255, 69, 0, 0.68)',
  'rgb(255, 120, 0)',
  'hsv(51, 100, 98)',
  'hsva(120, 40, 94, 0.5)',
  'hsl(181, 100%, 37%)',
  'hsla(209, 100%, 56%, 0.73)',
  '#c7158577'
]);

// 验证
const validated = async (): Promise<boolean> => {
  if (!nomalForm.value) {
    return false;
  }
  await nomalForm.value?.validate();
  return true;
};
// 暴露一个验证函数给父组件
defineExpose({ validated });
</script>
<style scoped lang="scss">
.nomal-workflow {
  display: flex;
  justify-content: center;
}

.icons-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;

  >div {
    margin: 10px;
    cursor: pointer;

    &:hover {
      color: #2d8cf0;
    }

    .el-icon-active {
      color: #2d8cf0;
    }
  }
}
</style>
